/* 3DGo Game
 * Copyright (C) 2008 Roman Hwang, Eugene Melnichek

 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation - version 2
 * of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "PhantomRunner.h"


PhantomRunner::PhantomRunner(const char *_programName, const char *_cmdLine)
{
	RunProcess(const_cast<char *>(_programName),const_cast<char *>( _cmdLine));
}

PhantomRunner::~PhantomRunner()
{
	Close();
}

bool PhantomRunner::RunProcess(char *_programName, char *_cmdLine)
{
	// Type declaration
	STARTUPINFO siStartInfo;
	BOOL bFuncRetn = FALSE; 
 
	// Set up members of the PROCESS_INFORMATION structure. 

	ZeroMemory( &m_processInfo, sizeof(PROCESS_INFORMATION) );
 
	// Set up members of the STARTUPINFO structure. 

	ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
	siStartInfo.cb = sizeof(STARTUPINFO); 
	siStartInfo.hStdError	= m_outputPipe.GetWriteEnd();
	siStartInfo.hStdOutput	= m_outputPipe.GetWriteEnd();
	siStartInfo.hStdInput	= m_inputPipe.GetReadEnd();
	siStartInfo.dwFlags |= STARTF_USESTDHANDLES;


    
	bFuncRetn = CreateProcess(_programName, 
      _cmdLine,       // command line 
      NULL,          // process security attributes 
      NULL,          // primary thread security attributes 
      TRUE,          // handles are inherited 
      0,             // creation flags 
      NULL,          // use parent's environment 
      NULL,          // use parent's current directory 
      &siStartInfo,  // STARTUPINFO pointer 
	  &m_processInfo);  // receives PROCESS_INFORMATION 

	return bFuncRetn != 0;
}

void PhantomRunner::Close()
{
	TerminateProcess(m_processInfo.hProcess, 0);
	TerminateThread(m_processInfo.hThread, 0);
	CloseHandle(m_processInfo.hProcess);
	CloseHandle(m_processInfo.hThread);
}

bool PhantomRunner::SendInput(const char *_input, int _size)
{
	return m_inputPipe.Write((LPVOID)const_cast<char*>(_input), _size);
}

bool PhantomRunner::GetOutput(char *_outputBuffer, int _bufferLength,unsigned long* _readSize)
{
	return m_outputPipe.Read((LPVOID)_outputBuffer, _bufferLength, _readSize);
}